package com.newtouch.cq.security.token;

import cn.hutool.core.collection.CollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class BaseAuthenticationTokenFilter extends OncePerRequestFilter {

	@Autowired
	private TokenCache<? extends UserDetails> tokenCache;
	@Autowired
    protected GenericTokenResolveAble tokenResolveAble;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
		List<String> tokenInfoArr = tokenResolveAble.resolveTokenDetail();
		if(CollUtil.isEmpty(tokenInfoArr)) {
//			throw new MccBizException(BaseExceptionEnum.USER_TOKEN_ERROR);
			chain.doFilter(request, response);
        	return;
		}
		String userKey = tokenInfoArr.get(0);
		String tokenKey = tokenInfoArr.get(1);
		UserDetails userDetails = tokenCache.loadByToken(userKey, tokenKey);
        if(null != userDetails) {
        	UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        	WebAuthenticationDetails details = tokenResolveAble.resolveDetails(request, tokenKey);
        	authentication.setDetails(details);
        	SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
			SecurityContextHolder.clearContext();
		}
        chain.doFilter(request, response);
    }


}
